// db/index.js
const mysql = require("mysql2/promise");
const { database } = require("../config");

// 数据库配置（从.env读取）
const config = {
    host: database.host,
    port: database.port,
    user: database.user,
    password: database.password,
    database: database.name,
    waitForConnections: true, // 连接超额是否等待
    connectionLimit: 10, // 连接池最大连接数
    queueLimit: 0
};

// 创建连接池
const pool = mysql.createPool(config);

// 测试数据库连接
async function testConnection() {
    try {
        const connection = await pool.getConnection();

        console.log("✅ 数据库连接成功");
        connection.release(); // 释放连接
    } catch (err) {
        console.log("❌ 数据库连接失败:", err.message);
    }
}

// 执行SQL语句的工具函数（封装增删改查）
async function executeSql(sql, params = []) {
    try {
        const [results] = await pool.execute(sql, params);
        return { success: true, data: results };
    } catch (err) {
        console.log("SQL执行错误:", err.message);
        return { success: false, error: err.message };
    }
}

module.exports = {
    pool,
    testConnection,
    executeSql
};
